from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车序列化器"""
    # 指定字段
    sku_id = serializers.IntegerField(label="商品 SKU 编号", min_value=1)
    count = serializers.IntegerField(label="商品数量", min_value=1)
    selected = serializers.BooleanField(label="商品是否勾选", default=True)

    def validate(self, attrs):
        # 获取字段
        sku_id = attrs["sku_id"]
        count = attrs["count"]

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError("商品 sku id 不存在")

        # 判断库存
        if count > sku.stock:
            raise serializers.ValidationError("库存不足")

        return attrs